package com.gxuwz.stats.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.gxuwz.stats.entity.BaseExcelDTO;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.service.UserService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public abstract class BaseExcelListener<T extends BaseExcelDTO> extends AnalysisEventListener<T> {
    protected List<T> dataList = new ArrayList<>();
    protected static final int BATCH_COUNT = 100;
    protected final UserService userService;

    public BaseExcelListener(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void invoke(T data, AnalysisContext context) {
        dataList.add(data);
        if (dataList.size() >= BATCH_COUNT) {
            saveData();
            dataList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
    }

    protected abstract void saveData();

    protected Integer getUserId(String username) {
        User user = userService.findByUsername(username);
//        User user = userService.getUserIdOrInsertUser(username);
        if (user == null) {
            throw new RuntimeException("用户不存在: " + username);
        }
        return user.getUserId();
    }
}
